﻿using System;
using System.Runtime.CompilerServices;
namespace Awaitable
{
    public class State_t<_Ty>
    {
        private Action _action;
        private _Ty _result;
        private bool _completed = false;
        public bool IsCompleted
        {
            get
            {
                return this._completed;
            }
        }
        public _Ty Result
        {
            get
            {
                return this._result;
            }
            set
            {
                this._result = value;
                this._completed = true;
            }
        }
        public void SetAction(Action act)
        {
            this._action = act;
        }
        public void Resume()
        {
            if (this._action != null) this._action.Invoke();
        }
    };
    public class Future_t<_Ty> : INotifyCompletion
    {
        public State_t<_Ty> State { get; }
        public bool IsCompleted
        {
            get
            {
                return this.State.IsCompleted;
            }
        }
        public Future_t(State_t<_Ty> st)
        {
            this.State = st;
        }
        public _Ty GetResult()
        {
            return this.State.Result;
        }
        void INotifyCompletion.OnCompleted(Action act)
        {
            this.State.SetAction(act);
        }
    };
    public class Promise_t<_Ty>
    {
        public State_t<_Ty> State { get; }
        public Promise_t()
        {
            this.State = new State_t<_Ty>();
        }
        public Future_t<_Ty> GetAwaiter()
        {
            return new Future_t<_Ty>(this.State);
        }
    };
}